package com.company.笔试.字符串压缩;

/**
 * @author ylr
 * @version 1.0.0
 * @ClassName Solution.java
 * @Description TODO  aabbcc  -> 2a2b2c
 * @createTime 2022年03月03日 19:33:00
 */
public class Solution {
    public static void main(String[] args) {
        System.out.println(getString("aabccdddde"));
    }
    public static String getString(String str){
        int length = str.length();
        char[] chars = str.toCharArray();
        int cnt = 1;
        int i = 0;
        StringBuilder res = new StringBuilder();
        while (i < length) {
            for (int j = i+1; j < length; j++) {  //j=4  5=d  6
                if (chars[i]==chars[j]){ //aa  cc   ddd
                    cnt++; //cnt =2            2      3
                }else if (chars[i]!=chars[j]&&cnt!=1){ //a!=b  cnt =2
                    res.append(cnt).append(chars[i]);  //2a  2ab2c3d
                    cnt =1;
                    i=j;//i=2  5  8
                    break;
                }else {
                    res.append(chars[i++]);//2ab  i=3
                    break;
                }
            }
            if (cnt!=1){
                res.append(cnt).append(chars[i]);
                break;
            }else if (length-1==i) {
                res.append(chars[i]);
                break;
            }
        }
        return res.toString();
    }

}
